<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Goods as GoodsModel;
use app\common\library\SearchLog;

/**
 * 商城接口
 * @ApiWeigh (87)
 */
class Goods extends Api
{
    protected $noNeedLogin = ['index', 'detail', 'category'];
    protected $noNeedRight = '*';

    /**
     * 商品分类列表
     *
     * @ApiTitle    (商品分类列表)
     * @ApiSummary  (获取商品分类列表)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
     "code": 1,
     "msg": "success",
     "data": [{
       "id": 1,
       "pid": 0,
       "name": "分类名称",
       "image": "分类图片"
     }]
     })
     */
    public function category()
    {
        $list = \app\common\model\GoodsCategory::where('status', 1)
            ->field('id,pid,name,image,status')
            ->order('weigh DESC,id DESC')
            ->select();
            
        // 处理图片路径
        foreach($list as &$item) {
            $item['image'] = cdnurl($item['image']);
        }
            
        $this->success('', $list);
    }

    /**
     * 商品列表
     *
     * @ApiTitle    (商品列表)
     * @ApiSummary  (获取商品列表，支持分页、搜索和分类筛选)
     * @ApiMethod   (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="per_page", type="integer", required=false, description="每页数量", default=10)
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词")
     * @ApiParams   (name="category_id", type="integer", required=false, description="分类ID", default=0)
     * @ApiParams   (name="order_field", type="string", required=false, description="排序字段:id=默认,sales=销量,price=价格,createtime=发布时间", default="id")
     * @ApiParams   (name="order_type", type="string", required=false, description="排序方向:desc=降序,asc=升序", default="desc")
     * @ApiReturn   ({
     "code": 1,
     "msg": "success",
     "data": {
       "total": 100,                     // 总记录数
       "per_page": 10,                   // 每页数量
       "current_page": 1,                // 当前页码
       "last_page": 10,                  // 最后一页页码
       "data": [{
         "id": 1,                        // 商品ID
         "title": "商品标题",            // 商品标题
         "cover_image": "商品封面",      // 商品封面图片
         "sales": 100,                   // 销量
         "min_price": "10.00",           // 最低价格
         "max_price": "20.00",           // 最高价格
         "freight_price": "运费",        // 运费
         “vip_min_price”: "会员最低价格",  // 会员最低价格
         "vip_max_price”: "会员最高价格",  // 会员最高价格
         "specs": [{                     // 商品规格列表
           "id": 1,                      // 规格ID
           "spec_name": "规格名称",      // 规格名称
           "price": "10.00",             // 规格价格
           "original_price": "20.00",    // 规格原价
           "stock": 100                  // 规格库存
         }]
       }]
     }
     })
     */
    
    public function index()
    {
        $page = $this->request->get('page', 1);
        $per_page = $this->request->get('per_page', 10);
        $keyword = $this->request->get('keyword', '');
        $category_id = $this->request->get('category_id', 0);
        $sort = $this->request->get('sort', '');

        // 记录搜索历史
        if ($keyword && $this->auth->id) {
            SearchLog::record($this->auth->id, $keyword, 'goods');
        }

        $where = ['status' => 1, 'deletetime' => null];
        
        if ($keyword) {
            $where[] = function($query) use ($keyword) {
                $query->where('title', 'LIKE', "%{$keyword}%")
                    ->whereOr('description', 'LIKE', "%{$keyword}%")
                    ->whereOr('category_id', 'IN', function($query) use ($keyword) {
                        $query->name('goods_category')
                            ->where('name', 'LIKE', "%{$keyword}%")
                            ->field('id');
                    });
            };
        }
        if ($category_id) {
            $where['category_id'] = $category_id;
        }
        $query = GoodsModel::with(['specs'])->where($where)
            ->field('id,title,cover_image,sales,createtime,status');
            
        // 根据排序参数设置排序方式
        $orderField = $this->request->get('order_field', 'id'); // 排序字段
        $orderType = $this->request->get('order_type', 'desc'); // 排序方向
        
        // 允许的排序字段
        $allowFields = [
            'id' => 'id',
            'sales' => 'sales',
            'time' => 'createtime'
        ];
        
        // 验证排序字段和方向
        $field = isset($allowFields[$orderField]) ? $allowFields[$orderField] : 'id';
        $type = strtolower($orderType) === 'asc' ? 'ASC' : 'DESC';
        
        // 价格排序特殊处理
        if ($orderField === 'price') {
            // 使用子查询获取最低价格
            $query->join('(SELECT goods_id, MIN(price) as min_price FROM gu_goods_spec GROUP BY goods_id) as gs', 'gs.goods_id = gu_goods.id', 'LEFT')
                ->order('gs.min_price ' . $type . ', gu_goods.id DESC');
        } else {
            $query->order($field . ' ' . $type . ',weigh DESC, id DESC');
        }
        
       
        $list = $query->page($page, $per_page)->select();
        $total = GoodsModel::with(['specs'])->where($where)->count();

        // 获取会员折扣
        $discount = 1;
        if ($this->auth->id) {
            $user = \app\common\model\User::get($this->auth->id);
            if ($user->vip_expire_time > time()) {
                // 获取会员折扣配置
                $vipConfig = \app\common\model\VipConfig::where('id', 1)->find();
                if ($vipConfig) {
                    $discount = $vipConfig->discount;
                }
            }
        }
        
        // 处理价格区间和图片路径
        foreach ($list as &$item) {
            $item->min_price = $item->min_price;
            $item->max_price = $item->max_price;
            $item->vip_min_price = round($item->min_price * $discount, 2);
            $item->vip_max_price = round($item->max_price * $discount, 2);
            $item->cover_image = cdnurl($item->cover_image);
        }
        $this->success('', [
            'total' => $total,
            'per_page' => $per_page,
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'data' => $list
        ]);
    }

    /**
     * 商品详情
     *
     * @ApiTitle    (商品详情)
     * @ApiSummary  (获取商品详细信息及其规格列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="商品ID")
     * @ApiReturn   ({
     "code": 1,
     "msg": "success",
     "data": {
       "id": 1,
       "title": "商品标题",
       "description": "商品描述",
       "content": "商品详情",
       "cover_image": "商品封面",
       "images": ["图片1", "图片2"],
       "sales": 100,
       "min_price": "10.00",
       "max_price": "20.00",
       "vip_min_price": "会员最低价格",
       "vip_max_price": "会员最高价格",
       "freight_price": "运费",
       "specs": [{
         "id": 1,
         "spec_name": "规格名称",
         "price": "10.00",
         "vip_price": "会员价",
         "original_price": "20.00",
         "stock": 100
       }]
     }
     })
     */
    public function detail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $goods = GoodsModel::with(['specs'])->where(['id' => $id, 'status' => 1])->find();
        if (!$goods) {
            $this->error('商品不存在');
        }

        // 处理图片路径
        $goods->cover_image = $goods->cover_image ? cdnurl($goods->cover_image) : '';
        $images = [];
        if ($goods->images) {
            foreach ($goods->images as $image) {
                if ($image) {
                    $images[] = cdnurl($image);
                }
            }
        }
        $goods->images = $images;
        
        // 获取会员折扣
        $discount = 1;
        if ($this->auth->id) {
            $user = \app\common\model\User::get($this->auth->id);
            if ($user->vip_expire_time > time()) {
                // 获取会员折扣配置
                $vipConfig = \app\common\model\VipConfig::where('id', 1)->find();
                if ($vipConfig) {
                    $discount = $vipConfig->discount;
                }
            }
        }
        
        // 处理会员价
        $goods = $goods->toArray();
        foreach ($goods['specs'] as &$spec) {
            $spec['vip_price'] = round($spec['price'] * $discount, 2);
        }
        
        $goods['vip_min_price'] = round($goods['min_price'] * $discount, 2);
        $goods['vip_max_price'] = round($goods['max_price'] * $discount, 2);

        // 过滤字段
        $allowFields = ['id', 'title', 'description', 'content', 'cover_image', 'images', 'sales', 'freight_price', 'min_price', 'max_price', 'specs', 'vip_min_price', 'vip_max_price'];
        $goods = array_intersect_key($goods, array_flip($allowFields));

        $this->success('', $goods);
    }

    /**
     * 商品库存
     *
     * @ApiTitle    (商品规格库存)
     * @ApiSummary  (获取指定商品规格的库存数量)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="商品ID")
     * @ApiParams   (name="spec_id", type="integer", required=true, description="规格ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "stock": 100
        }
      })
     */
    public function stock()
    {
        $id = $this->request->get('id');
        $spec_id = $this->request->get('spec_id');
        if (!$id || !$spec_id) {
            $this->error('参数错误');
        }

        $spec = \app\common\model\GoodsSpec::where([
            'id' => $spec_id,
            'goods_id' => $id
        ])->find();

        if (!$spec) {
            $this->error('规格不存在');
        }

        $this->success('', ['stock' => $spec->stock]);
    }
}